<template>
  <div
    id="cover-image"
    class="relative w-full b-rd-5 overflow-hidden flex"
    :style="{ aspectRatio: ratio }"
  >
    <Transition>
      <n-image v-if="loaded" :src="props.url" id="feed-img" preview-disabled object-fit="cover" :width="`100%`" />
      <div
        v-else
        class="w-full absolute"
        flex="~ justify-center items-center"
        :style="{ aspectRatio: ratio }"
      >
        <SpellaiShimmer />
      </div>
    </Transition>

    <div id="user-info" class="absolute bottom-0 w-full h10 flex items-center pl-4 text-3">
      <n-avatar :src="props.userIcon" alt="用户头像" class="mr-2" round :size="20" />
      <span class="font-700">{{ props.userName }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { NAvatar, NImage } from 'naive-ui'
import SpellaiShimmer from '@/components/SpellaiShimmer.vue'
const props = defineProps<{
  url?: string
  userIcon?: string
  userName?: string
  width?: number
  height?: number
}>()
const loaded = ref(false)
const ratio = computed(() => {
  return props.width! / props.height!
})
onBeforeMount(() => {
  new Promise((resolve) => {
    const image = new Image()
    image.src = props.url || ''
    if (image.complete) {
      loaded.value = true
      resolve(true)
      return
    }

    image.onload = () => {
      loaded.value = true
      resolve(true)
    }

    image.onerror = (error) => {
      console.error(props.url, error)
      loaded.value = true
      resolve(true)
    }
  })
})
</script>

<style scoped>
#cover-image {
  #user-info {
    background: linear-gradient(transparent, #000000ad);
  }
}
.v-enter-active,
.v-leave-active {
  opacity: 1;
  transition: all 0.4s linear;
  will-change: opacity;
}

.v-enter-from,
.v-leave-to {
  opacity: 0;
  will-change: opacity;
}
</style>
